package com.kuang.demo01;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @program: juc
 * @description:基本的卖票例子
 * @author: 陈恩涛
 * @create: 2021-01-28 14:58
 **/

/*
* 真正的多线程开发，公司中的开发，降低耦合
* 线程就是一个单独的资源类，没有任何附属的操作！
* 1、属性
* 2、方法
* */
public class SaleTicketDemo02 {
    //并发，多线程操作同一个资源类,把资源类丢入线程
    public static void main(String[] args) {
        Ticket2 ticket = new Ticket2();

        //@FunctionalInterface 函数式接口
        //jdk1.8 lamda表达式 (参数)->{代码}
        new Thread(() -> {for (int i = 0; i < 40; i++) ticket.sale();},"窗口A").start();
        new Thread(() -> {for (int i = 0; i < 40; i++) ticket.sale();},"窗口B").start();
        new Thread(() -> {for (int i = 0; i < 40; i++) ticket.sale();},"窗口C").start();

    }

}

//资源类 OOP

//1、Lock lock = new ReentrantLock();
//2、加锁
//3、解锁
class Ticket2{
    private int number = 50;

    Lock lock = new ReentrantLock();

    public void sale(){

        lock.lock(); //加锁

        try {
            //业务代码
            if (number > 0) {
                System.out.println(Thread.currentThread().getName()+"卖出了第"+number--+"张票！剩余："+number+"张票！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock(); //解锁
        }
    }

}

